<template>
    <div class="app-container add">
        <CommonHeader title="入库单新增" :isShowBack="true" />
        <div class="add-wrap">
            <div class="form-box">
                <div class="form-title">
                    基本信息
                </div>
                <el-form :model="formData" ref="formData" :rules="rules" inline-message label-width="0" label-position="left">
                    <el-form-item prop="orderNumber">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>入库单号</div>
                            <div class="select-wrap" @click="showModal">
                                <span class="val" v-if="formData.orderNumber">{{ formData.orderNumber }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="warehouseCode">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>仓库名称</div>
                            <div class="select-wrap" @click="selectWareHousu">
                                <span class="val" v-if="formData.warehouseName">{{ formData.warehouseName }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="relateType">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>关联单据类型</div>
                            <div class="select-wrap" @click="billModalShow = true">
                                <span class="val" v-if="formData.relateTypeName">{{ formData.relateTypeName }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="relateOrders">
                        <div class="form-item">
                            <div class="label">
                                <span class="required"></span>关联单号
                                <img src="@/assets/images/scan02.png" alt="" class="scan" @click.stop="handleScanCode">
                            </div>
                            <div class="select-wrap" @click="toRefType()">
                                <span class="val" v-if="formData.relateOrders">{{ formData.relateOrders }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="planTime">
                        <div class="form-item">
                            <div class="label"><span class="required"></span>计划入库时间</div>
                            <div class="select-wrap" @click="dateShow = true">
                                <span class="val" v-if="formData.planTime">{{ formData.planTime }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="applyPerson">
                        <div class="form-item">
                            <div class="label">
                                <!-- <span class="required"></span> -->
                                申请人</div>
                            <div class="select-wrap" @click="userModalShow = true">
                                <span class="val" v-if="formData.applyPersonName">{{ formData.applyPersonName }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="warehouseManagerName">
                        <div class="form-item">
                            <div class="label">
                                <!-- <span class="required"></span> -->
                                仓管员</div>
                            <div class="select-wrap" @click="warehouseUserModalShow = true">
                                <span class="val" v-if="formData.warehouseManagerName">{{ formData.warehouseManagerName }}</span>
                                <span class="txt" v-else>请选择</span>
                                <i class="el-icon-arrow-down down-icon"></i>
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <!--  -->
            <div class="form-box">
                <div class="form-title">备注信息</div>
                <div class="remark-wrap">
                    <el-input type="textarea" :rows="2" v-model="formData.remark" placeholder="请输入备注信息" class="textarea"></el-input>
                </div>
            </div>
        </div>
        <div class="model-footer-wrap">
            <van-button
            type="primary"
            block
            round
            color="#548af1"
            size="normal"
            :loading="btnLoading"
            loading-text="正在提交..."
            @click="submitAdd()"
            >提交</van-button
            >
        </div>
        <!-- 仓库 -->
        <van-popup v-model="wareHouseModalShow" position="bottom">
            <van-picker
                title="仓库列表"
                show-toolbar
                :columns="wareHouseList"
                value-key="warehouseName"
                @confirm="onConfirm"
                @cancel="wareHouseModalShow = false"
            />
        </van-popup>
        <!-- 关联单据类型 -->
        <van-popup v-model="billModalShow" position="bottom">
            <van-picker
                title="关联单据类型"
                show-toolbar
                :columns="billList"
                value-key="typeName"
                @confirm="onBillConfirm"
                @cancel="billModalShow = false"
            />
        </van-popup>
        <!-- 申请人选择 -->
        <van-popup v-model="userModalShow" position="bottom">
            <van-picker
                title="申请人列表"
                show-toolbar
                :columns="userList"
                value-key="nickname"
                @confirm="onUserConfirm"
                @cancel="userModalShow = false"
            />
        </van-popup>
        <!-- 仓管员 -->
        <van-popup v-model="warehouseUserModalShow" position="bottom">
            <van-picker
                title="仓管员列表"
                show-toolbar
                :columns="warehouseUserList"
                value-key="nickname"
                @confirm="onWarehouseUserConfirm"
                @cancel="warehouseUserModalShow = false"
            />
        </van-popup>
        <!-- 时间选择 -->
        <van-calendar v-model="dateShow" color="#548AF1" :min-date="minDate" @confirm="onDateConfirm" />
        <ruleDialog
        :show.sync="modalShow"
        :value.sync="formData.orderNumber"
        @confirm="confirm"
        ></ruleDialog>
    </div>
</template>
<script>
import CommonHeader from "@/components/CommonHeader";
import { getRelateType, getUserList, getWarehouseUserList, pdaAdd, productOrdersList, materialListByRelate, workordersSimple, getDefaultWarehouse  } from '@/api/inventory'
import { queryRepositoriesIsolationList, queryAllWareHoseList } from '@/api/allocation'
import { getUserInfo } from '@/api/user'
import ruleDialog from "./components/ruleDialog.vue";
import { Toast } from "vant";

export default {
  components: { CommonHeader, ruleDialog },
  data() {
    return {
        minDate: new Date(2010, 0, 1),
        btnLoading: false,
        formData: {
            orderNumber: '',
            warehouseName: '',
            warehouseCode: '',
            applyPersonName: '',
            applyPerson: '',
            warehouseManagerName: '',
            relateTypeName: '',
            relateType: '',
            relateOrders: '',
            planTime: '',
            inOrOutType: 'purchase' //出入库类型（purchase:采购入库单 applicationReturn:生产退料入库 workOrderComplete:生产入库 ）
        },
        rules: {
            orderNumber: [
                { required: true, message: '请选择', trigger: 'change' },
            ],
            warehouseName: [
                { required: true, message: '请选择', trigger: 'change' },
            ],
            warehouseCode: [
                { required: true, message: '请选择', trigger: 'change' },
            ],
            relateType: [
                { required: true, message: '请选择', trigger: 'change' },
            ],
            relateOrders: [
                { required: true, message: '请选择', trigger: 'change' },
            ],
            planTime: [
                { required: true, message: '请选择', trigger: 'change' },
            ],
            applyPerson: [
                { required: false, message: '请选择', trigger: 'change' },
            ],
            warehouseManagerName: [
                { required: false, message: '请选择', trigger: 'change' },
            ],

        },
        wareHouseModalShow: false,
        wareHouseList: [],
        warehouseUserList: [],
        warehouseUserModalShow: false,
        billModalShow: false,
        billList: [],
        userModalShow: false,
        userList: [],
        dateShow: false,
        modalShow: false,
        userInfo: {}
    }

  },
  async created() {
    await this.getUserInfo()
    this.getAllWarehouse()
    // this.getRelateTypeList()
    this.getUserList()
    this.initrelateType()
  },
  methods: {
    // 判断是否有默认仓库
    getDefaultWarehouseInfo() {
      getDefaultWarehouse({ type: 1 }).then(res => {
        const { data, code } = res.data
        if(code === '200' && data && data.warehouseCode) {
          this.onConfirm(data)
        }
      })
    },
    async initrelateType(){
      const formData = JSON.parse(sessionStorage.getItem('currentFormData')) || {}
      if(formData.orderNumber){
        this.formData = formData
      } else {
        this.getDefaultWarehouseInfo()
      }
      // 计划时间默认当前日期
      if(!formData.planTime){
        this.formData.planTime = this.formatDate(new Date());
      }
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      const list =  await this.getRelateTypeList();
      const wList = await this.getAllWarehouse();
      loading.close();
      if(this.$route.query.relateType){
        const data = list.filter(item=>item.typeCode == formData.relateType)
        const wdata = wList.filter(item=>item.warehouseName == formData.warehouseName)
        this.onBillConfirm(data[0])
        if (wdata.length > 0) {
           this.onConfirm(wdata[0],'auto')
        }
        this.initRefNo()
      }
    },
    initRefNo(){
      if(Object.keys(this.$store.state.routerQuery.refOderList).length >0){
        if(this.formData.relateType == "purchaseReceipt"){
          this.formData.relateOrders = this.$store.state.routerQuery.refOderList.receiptCode
          this.getMaterialListByRelate(this.$store.state.routerQuery.refOderList.receiptCode)
        }else{
          this.formData.relateOrders = this.$store.state.routerQuery.refOderList.purchaseCode
          this.getMaterialListByRelate(this.$store.state.routerQuery.refOderList.purchaseCode)
        }
        sessionStorage.setItem("currentFormData", JSON.stringify(this.formData));
      }
    },
    toRefType(){
      if(!this.formData.relateType){
        Toast('请选择关联类型')
        return
      }
      sessionStorage.setItem('currentFormData',JSON.stringify(this.formData))
      this.$router.push({
        path:"/addRefType",
        query:{
          relateType: this.formData.relateType
        }
      })
    },
    // 打开入库单号
    showModal() {
      this.modalShow = true;
    },
    // 获取当前用户账号
    async getUserInfo() {
        const result = await getUserInfo()
        const { code, data, message } = result.data || {}
        if (+code === 200) {
            this.userInfo = data
        }
    },
    // 点击扫码按钮进行扫码
    async handleScanCode() {
        if(!this.formData.relateType) {
            Toast('请先选择关联单据类型')
            return
        }
      // 生产环境和开发环境
      const that = this;
      if (process.env.NODE_ENV === "production") {
        window.flutter_inappwebview.callHandler("qrCode").then((res) => {
            if (!res) return;
            if(this.formData.relateType === 'purchaseReceipt') { //采购收货单
                that.getProductOrdersList(res)
            } else if(this.formData.relateType === 'purchaseOrder') { //生产订单
                
                that.getWorkordersSimple(res)
            }
        });
      } else {
        if(this.formData.relateType === 'purchaseReceipt') { //采购收货单
            that.getProductOrdersList("CGSH20230710001")
        } else if(this.formData.relateType === 'purchaseOrder') { //生产订单
            that.getWorkordersSimple("CGSH20230710001")
        }
      }
    },
     // //采购收货单
     async getProductOrdersList(orderNo) {
        const result = await productOrdersList({ receiptCode: orderNo, states: '2,3' })
        const { code, data, message } = result.data || {}
        if (+code === 200) {
            if (data.records && data.records.length > 0) {
                data.records.filter(item => {
                    if (item.receiptCode === orderNo) {
                        this.formData.relateOrders = item.receiptCode
                        this.getMaterialListByRelate(item.receiptCode)
                    }
                })
            } else {
                Toast('扫描的单据不符合关联条件')
            }
        } else {
            Toast(message)
        }
    },
    async getWorkordersSimple(orderNo) {
        const result = await workordersSimple({ purchaseCode: orderNo, state: '2,3' })
        const { code, data, message } = result.data || {}
        if (+code === 200) {
            if (data.records && data.records.length > 0) {
                data.records.filter(item => {
                    if (item.purchaseCode === orderNo) {
                        this.formData.relateOrders = item.purchaseCode
                        this.getMaterialListByRelate(item.purchaseCode)
                    }
                })
            } else {
                Toast('扫描的单据不符合关联条件')
            }
        } else {
            Toast(message)
        }
    },
    // 通过关联单号查询物料信息和批次信息
    async getMaterialListByRelate(orderNumber) {
        const params = {
            relateOrder: orderNumber,
            relateType: this.formData.relateType
        }
        const loading = this.$loading({
            lock: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        const result = await materialListByRelate(params)
        const { code, data, message } = result.data || {}
        if (+code === 200) {
            this.materialDetails = data.map(item => {
                return {
                    productCode: item.productCode,
                    planAmount: item.planAmount,
                    actualAmount: item.actualAmount,
                    skuId: item.skuId,
                    skuName: item.skuName,
                    skuCode: item.skuCode,
                    materialRemark: item.materialRemark,
                    materialType: item.materialFields ? item.materialFields.typeName : item.materialType,
                    type: item.materialFields ? item.materialFields.type : item.type,
                    stockMaterialDetaiList: (item.barCodeDTOList || []).map(citem=>{
                        return{
                            ...citem,
                            purchaseBatchNumber : item.purchaseBatchNumber
                        }
                    })
                }
            })
            loading.close();
        } else {
            loading.close();
        }
    },
    // 打开仓库弹框
    selectWareHousu() {
      this.wareHouseModalShow = true;
    },
    // 获取所有的仓库列表
    async getAllWarehouse () {
        return new Promise( async(resolve, reject) => {
            const result = await queryRepositoriesIsolationList()
            const { code, data = {}, message } = result.data || {}
            if (+code === 200) {
                const { records = [] } = data
                this.wareHouseList = records
            } else {
                Toast.success('获取仓库列表失败')
            }
            resolve(data.records)
        })
    },
    // 关联单据类型
    async getRelateTypeList () {
        return new Promise( async(resolve, reject) => {
            const result = await getRelateType()
            const { code, data, message } = result.data || {}
            if (+code === 200) {
                this.billList = data
            } else {
                Toast.success(message)
            }
            resolve(data)
        })
    },
    // 申请人列表
    async getUserList () {
      const result = await getUserList()
      const { code, data, message } = result.data || {}
      if (+code === 200) {
        this.userList = data.records || []
        // 默认当前账号
        if(!!this.userInfo && this.userInfo.id && this.userList.length > 0) {
            this.userList.forEach(item => {
                if(item.id === this.userInfo.id) {
                    this.formData.applyPersonName = item.nickname
                    this.formData.applyPerson = item.username
                }
            })
        }
      } else {
        Toast.success(message)
      }
    },
    // 仓管员列表
    async getWarehouseUserList (id) {
      const result = await getWarehouseUserList(id)
      const { code, data, message } = result.data || {}
      if (+code === 200) {
        this.warehouseUserList = data || []
        // 默认当前账号
        if(!!this.userInfo && this.userInfo.id && this.warehouseUserList.length > 0) {
            this.warehouseUserList.forEach(item => {
                if(item.id === this.userInfo.id) {
                    this.formData.warehouseManagerName = item.nickname
                    this.formData.warehouseManager = item.username
                }
            })
        }
      } else {
        Toast.success(message)
      }
    },
    // 选中仓管员
    onWarehouseUserConfirm(val) {
      this.formData.warehouseManagerName = val.nickname;
      this.formData.warehouseManager = val.username;
      this.warehouseUserModalShow = false;
    },
    // 选中关联单据类型
    onBillConfirm(val) {
      this.formData.relateTypeName = val.typeName;
      this.formData.relateType = val.typeCode;
      this.formData.relateOrders = ''
      this.billModalShow = false;
    },
    // 选中仓库
    onConfirm(val, type) {
      if(type == 'auto'){
        this.formData.warehouseManagerName =  "";
        this.formData.warehouseManager = "";
      }
      this.formData.warehouseName = val.warehouseName;
      this.formData.warehouseCode = val.warehouseCode;
      this.formData.warehouseId = val.warehouseId;
      this.wareHouseModalShow = false;
      this.formData.warehouseManagerName = ''
      this.getWarehouseUserList(val.warehouseId)
    },
    // 选中申请人
    onUserConfirm(val) {
      this.formData.applyPersonName = val.nickname;
      this.formData.applyPerson = val.username;
      this.userModalShow = false;
    },
    formatDate(val) {
        const date = new Date(val);
        const Y = date.getFullYear();
        const M = date.getMonth() + 1;
        const D = date.getDate();
        const H = date.getHours();
        const Min = date.getMinutes();
        const S = date.getSeconds();
        const formattedDate = `${Y}-${(M < 10 ? '0' : '') + M}-${(D < 10 ? '0' : '') + D} ${(H < 10 ? '0' : '') + H}:${(Min < 10 ? '0' : '') + Min}:${(S < 10 ? '0' : '') + S}`;
        return formattedDate
    },
    onDateConfirm(date) {
      this.dateShow = false;
      this.formData.planTime = this.formatDate(date);
    },
    // 确定单号
    confirm(val) {
      this.formData.orderNumber = val;
    },
    // 提交新增保存
    async submitAdd() {
        this.$refs.formData.validate((valid) => {
            if (valid) {
                this.addPda()
            }
        });
    },
    async addPda() {
        this.btnLoading = true
        const params = {
            ...this.formData,
            materialDetails: this.materialDetails
        }
        const result = await pdaAdd(params)
        this.btnLoading = false
        const { code, data, message } = result.data || {}
        if (+code === 200) {
            Toast.success('新增成功')
            sessionStorage.removeItem('currentFormData')
            this.$router.push({
                path:"/allocationDetail",
                query:{
                    id: data
                }
            })
        } else {
            Toast(message)
        }
    }
  }
}
</script>

<style lang="scss" >

.add-wrap{
    .el-form-item__error{
        position: absolute !important;
        top: 25px;
        right: 30px;
    }
    .el-textarea__inner{
        border: none !important;
        text-align: right !important;
    }
}
</style>
<style lang="scss" scoped>
.header-top{
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    z-index: 2;
}
.add-wrap{
    padding-top: 44px;
    padding-bottom: 80px;
    .form-box{
        margin: 12px 12px 0;
        background-color: #ffffff;
        border-radius: 4px;
        .el-form-item{
            margin-bottom: 0 !important;

        }
        .form-title{
            font-size: 16px;
            margin: 0 7px;
            height: 40px;
            display: flex;
            align-items: center;
            border-bottom: 1px #F3F3F3 solid;
            position: relative;
            padding-left: 8px;
            &::before{
                content: '';
                width: 4px;
                height: 14px;
                background-color: #548AF1;
                position: absolute;
                left: 0;
                top: 13px;
            }
        }
        .form-item{
            margin: 0 7px;
            padding: 0 7px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px #F3F3F3 dotted;
            font-size: 13px;
            color: #333333;
            .label{
                display: flex;
                align-items: center;
                .required{
                    content: '';
                    color: #FF0000;
                    display: inline-block;
                    width: 6px;
                    height: 6px;
                    background: url('../../assets/images/required.png') no-repeat;
                    background-size: 100% 100%;
                    margin-right: 4px;
                }
                .scan{
                    width: 19px;
                    height: 19px;
                    margin-left: 9px;
                }
            }
            .info-wrap{
                text-align: right;
                .code{
                    color: #548AF1;

                }
            }
            input{
                width: 100%;
                border: none;
                text-align: right;
            }
            .select-wrap{
                color: #999999;
                .val{
                    color: #333333;
                }
                i{
                    margin-left: 5px;
                    color: #909090;
                }
            }
        }
        .remark-wrap{
            padding: 6px 0;
            .textarea{
                // height: 35px;
                width: 100%;
                border: none;
                font-size: 14px;
                color: #333333;

            }
        }
    }

}
</style>
